<?php
            
use app\model\Record; 
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 


use PHPExcel;

/**
 * Author: cbw
 * Desc: 教培
 * Time: 2021/12/6 10:51 上午
 * Email: 17854288794@163.com
 */

class Flag_Page extends PluginWebPage
{
    /**
     * Desc:礼品记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 10:53 上午
     */
    public function main()
    {
        $action = 8;
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $name = isset($_P['name'])?trim($_P['name']):'';
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $status = isset($_P['status'])?$_P['status']:0;
        $shangjiaid = isset($_P['shangjiaid'])?$_P['shangjiaid']:0;
        $gift_id = isset($_P['gift_id'])?$_P['gift_id']:0;
        $recordid = isset($_P['recordid'])?$_P['recordid']:0;
        $shangjia = EducationModel::getShangjiaList();
        $gift_type = isset($_P['gift_type'])?$_P['gift_type']:0;
        array_unshift($shangjia,['id'=>0,'name'=>'全部商家']);

        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
            $starttime = strpos($_P['createtime']['start'],' ')?strtotime($_P['createtime']['start']):$_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$starttime);
        }
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $endtime = strpos($endtime,' ')?strtotime($endtime):$endtime;
        $end_day = date("Y-m-d H:i:s",$endtime);
        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $type_arr = EducationModel::getFlagTypeCount($themeid);
        $prize_arr = EducationModel::getGiftFlagCount($themeid);


        $gift_type_list1 = [];
        $setting1 = EducationModel::getRewardByWhere(['themeid'=>$themeid]);
        $tuan_gift_info1 = json_decode($setting1['tuan'],true);
        $order_gift_info1 = json_decode($setting1['order'],true);
        if (is_array($tuan_gift_info1)){
            $tuan_gift_id1 = 0;
            foreach ($tuan_gift_info1 as $key => $val){
                if ($val['key']=='id'){
                    $tuan_gift_id1 = $val['val'];
                }
            }
        }

        $type_list1 = [
            "title"=>'成团礼',
            "gift_id"=>$tuan_gift_id1,
        ];
        array_push($gift_type_list1,$type_list1);
        if ($order_gift_info1 && is_array($order_gift_info1)){
            foreach ($order_gift_info1 as $key => $val){
                $gift_id1 = $val['gift_id'];
                $temp_array1 = [
                    "title"=>'邀请'.$val['invite'].'人礼',
                    "gift_id"=>$gift_id1,
                ];
                array_push($gift_type_list1,$temp_array1);
            }
        }



        $page_total = EducationModel::getUserGift($themeid,$shangjiaid,$search_data,0,0,$start_day,$end_day,$gift_type,$gift_id,$status,$recordid,true);
        $list = EducationModel::getUserGift($themeid,$shangjiaid,$search_data,$page_start,$page_size,$start_day,$end_day,$gift_type,$gift_id,$status,$recordid);
        foreach ($list as $kk => $vv)
        {
            if ($vv['status']==2){
                $new_gift_id = $vv['gift_id'];
                $list[$kk]['desc'] = '';
                foreach ($gift_type_list1 as $k1 => $val1){
                    if ($val1['gift_id']==$new_gift_id){
                        $list[$kk]['desc'] = $val1['title'];
                    }
                }
            }else{
                $list[$kk]['desc'] = '';
            }
            $check_name = '';
            if ($vv['workerid']){
                $r = Worker::getWokerName($_S,$themeid,$vv['workerid']);
                $check_name=$r['workername']==1?'后台管理员':$r['workername'];
            }
            $list[$kk]['verify_name'] = $check_name;
        }


        $total = $page_total;
        //导出礼品记录
        if (checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID', 'nickname' => '微信昵称','username' => '姓名', 'mobile' => '电话',
                'name' => '礼品名称',  'status' => '礼品类型','hexiao'=>'核销信息','shangjainame'=>'提供商家',
                'created_at'=>'中奖时间'
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
                $condition="";
                if ($shangjiaid){
                    $condition .= " and a.shangjiaid=$shangjiaid ";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
                }
                if ($gift_id){
                    $condition .= " and a.gift_id=$gift_id ";
                }
                if ($recordid){
                    $condition .= " and a.order_id=$recordid ";
                }
                if ($status){
                    $condition .= " and a.status=$status ";
                }
                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }
                if ($gift_type){
                    $condition .= " and a.status=$gift_type";
                }

                $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                $sql = " SELECT a.id,a.uid,a.status,a.gift_id,a.created_at,a.updated_at,a.shangjiaid,a.workerid,b.avatar,b.nickname,b.username,b.mobile,c.name,d.name as shangjainame FROM "
                    .tablename(t_shangjia_user_gift)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia_gift)." AS c ON a.gift_id=c.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_record)." AS e ON  e.themeid=$themeid and a.uid=e.uid".
                    " WHERE a.themeid=$themeid and a.can_use=1 and e.status=1".$condition.
                    "   order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);

                //导出判断礼品类型
                $gift_type_list1 = [];
                $setting1 = EducationModel::getRewardByWhere(['themeid'=>$themeid]);
                $tuan_gift_info1 = json_decode($setting1['tuan'],true);
                $order_gift_info1 = json_decode($setting1['order'],true);
                if ($tuan_gift_info1){
                    foreach ($tuan_gift_info1 as $key => $val){
                        if ($val['key']=='id'){
                            $tuan_gift_id1 = $val['val'];
                        }
                    }
                }
                $type_list1 = [
                    "title"=>'成团礼',
                    "gift_id"=>$tuan_gift_id1,
                ];
                array_push($gift_type_list1,$type_list1);
                if ($order_gift_info1 && is_array($order_gift_info1)){
                    foreach ($order_gift_info1 as $key => $val){
                        $gift_id1 = $val['gift_id'];
                        $temp_array1 = [
                            "title"=>'邀请'.$val['invite'].'人礼',
                            "gift_id"=>$gift_id1,
                        ];
                        array_push($gift_type_list1,$temp_array1);
                    }
                }
                foreach ($list as $kk => $vv)
                {
                    if ($vv['status']==2){
                        $new_gift_id = $vv['gift_id'];
                        $list[$kk]['desc'] = '';
                        foreach ($gift_type_list1 as $k1 => $val1){
                            if ($val1['gift_id']==$new_gift_id){
                                $list[$kk]['desc'] = $val1['title'];
                            }
                        }
                    }else{
                        $list[$kk]['desc'] = '';
                    }
                    if ($vv['workerid']){
                        $r = Worker::getWokerName($_S,$themeid,$vv['workerid']);
                        $check_name=$r['workername']==1?'后台管理员':$r['workername'];
                        $list[$kk]['hexiao'] = '已核销；员工【'.$check_name.'】在'.$vv['updated_at'].'核销';
                    }else{
                        $list[$kk]['hexiao'] = '未核销';
                    }
                }
                //导出判断礼品类型

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            switch ($row['status']){
                                case 1:
                                    $row['status'] = '赠品';
                                    break;
                                case 2:
                                    $row['status'] = $row['desc'];
                                    break;
                                default:
                                    break;
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
                //}
            }
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            //新版本导出合并
            Util::WxJump($_S,$html,'礼品记录',$themeid,$is_end,$pagesize);
        }
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/education/flag/main', $return_clicent);
    }

    /**
     * Desc:优惠券记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 10:53 上午
     */
    public function coupon()
    {
        $action = 9;
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $name = isset($_P['name'])?trim($_P['name']):'';
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $shangjiaid = isset($_P['shangjiaid'])?$_P['shangjiaid']:0;
        $gift_id = isset($_P['gift_id'])?$_P['gift_id']:0;
        $recordid = isset($_P['recordid'])?$_P['recordid']:0;
        $shangjia = EducationModel::getCouponFromCount($themeid);
        $gift_type = isset($_P['gift_type'])?$_P['gift_type']:0;


        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
            $starttime = strpos($_P['createtime']['start'],' ')?strtotime($_P['createtime']['start']):$_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$starttime);
        }
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $endtime = strpos($endtime,' ')?strtotime($endtime):$endtime;
        $end_day = date("Y-m-d H:i:s",$endtime);

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $type_arr = EducationModel::getFlagTypeCount($themeid);
        $prize_arr = EducationModel::getGiftFlagCount($themeid);
        $page_total = EducationModel::getUserCouponFlag($themeid,$shangjiaid,$search_data,0,0,$start_day,$end_day,$recordid,true);
        $list = EducationModel::getUserCouponFlag($themeid,$shangjiaid,$search_data,$page_start,$page_size,$start_day,$end_day,$recordid);
        $total = $page_total;
        //导出优惠券记录
        if (checksubmit('export_submit', true)){
            $count = $total;
            $page_limit =2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'uid' => 'UID', 'nickname' => '昵称','username' => '姓名', 'mobile' => '电话',
                'name' => '优惠券名称', 'price'=>'优惠券金额', 'shangjainame' => '优惠券获取渠道','status' => '状态',
                'created_at'=>'领取时间'
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
            $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                $condition="";
                if ($shangjiaid){
                    $condition .= " and a.shangjiaid=$shangjiaid ";
                }
                if ($recordid){
                    $condition .= " and a.order_id=$recordid ";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
                }
                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }


                $sql = " SELECT a.uid,a.status,a.created_at,a.shangjiaid,b.avatar,b.nickname,b.username,b.mobile,c.name,c.price,d.name as shangjainame FROM ".tablename(t_shangjia_user_coupon)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia_coupon)." AS c ON a.coupon_id=c.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_record)." AS e ON e.id=a.order_id and  e.themeid=$themeid".
                    " WHERE a.themeid=$themeid ".$condition.
                    "  order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            switch ($row['status']){
                                case 1:
                                    $row['status'] = '未使用';
                                    break;
                                case 2:
                                    $row['status'] = '已使用';
                                    break;
                                default:
                                    break;
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
//                }
            }
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            //新版本导出合并
            Util::WxJump($_S,$html,'优惠券领取记录',$themeid,$is_end,$pagesize);
        }
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/education/flag/coupon', $return_clicent);
    }

    /**
     * Desc:课程选择记录
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2021/12/8 10:53 上午
     */
    public function course()
    {
        $action = 10;
        global $_G,$_P,$_S,$_C;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $shangjiaid = isset($_P['shangjiaid'])?$_P['shangjiaid']:0;
        $gift_id = isset($_P['gift_id'])?$_P['gift_id']:0;
        $recordid = isset($_P['recordid'])?$_P['recordid']:0;
//        $shangjia = EducationModel::getShangjiaList();
        $shangjia = EducationModel::getSjRealSelectedCourseTotal($themeid);


        $gift_type = isset($_P['gift_type'])?$_P['gift_type']:0;
//        array_unshift($shangjia,['id'=>0,'name'=>'全部商家']);

        if (empty($_P['createtime']['start'])){
            $starttime =  $start_day =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
            $start_day =  date('Y-m-d H:i:s',$start_day);
        }else{
            $starttime = strpos($_P['createtime']['start'],' ')?strtotime($_P['createtime']['start']):$_P['createtime']['start'];
            $start_day = date("Y-m-d H:i:s",$starttime);
        }
        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        $endtime = strpos($endtime,' ')?strtotime($endtime):$endtime;
        $end_day = date("Y-m-d H:i:s",$endtime);

        $search_data = isset($_P['search_data'])?$_P['search_data']:'';
        if ($search_data){
            $search_data = '%'.$search_data.'%';
        }

        $page_total = EducationModel::getUserCourseFlag($themeid,$shangjiaid,$search_data,0,0,$start_day,$end_day,$recordid,1,0,true);
        $list = EducationModel::getUserCourseFlag($themeid,$shangjiaid,$search_data,$page_start,$page_size,$start_day,$end_day,$recordid);
        foreach ($list as $key => $val){
            $check_name = '';
            if ($val['workerid']){
                $r = Worker::getWokerName($_S,$themeid,$val['workerid']);
                $check_name=$r['workername']==1?'后台管理员':$r['workername'];
            }
            $list[$key]['verify_name'] = $check_name;
        }
        $total = $page_total;
        //导出课程校区记录
        if (checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = ['uid' => 'UID', 'nickname' => '昵称','username' => '姓名', 'mobile' => '电话',
                'form_nickanme'=>'邀约人微信昵称'];
            if (!empty($config['datetime'])) {
                $header['datetime']= $config['datetime'];
            }
            if (!empty($config['address'])) {
                $header['raddress'] = $config['address'];
            }
            if (!empty($config['formtwo'])) {
                $header['formtwo'] = $config['formtwo'];
            }
            if (!empty($config['addinfo'])) {
                $header['addinfo']= $config['addinfo'];
            }
            if (!empty($config['shops']) && $config['shopstype']!=8 ) {
                $header['option'] = $config['shops'];
            }
            $header2 = array('name' => '课程名称',  'address' => '上课地址','shangjianame'=>'提供商家',
                'status'=>'核销状态','check_name'=>'课程核销人','checked_at'=>'课程核销时间',
                'workenname'=>'员工',
                'created_at'=>'创建时间'
            );
            $header = array_merge($header,$header2);
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";
//            for ($j = 1; $j <= $pagesize; $j++) {
                $condition="";
                if ($shangjiaid){
                    $condition .= " and a.shangjiaid=$shangjiaid ";
                }
                if ($search_data){
                    $condition .= " AND b.nickname LIKE '".$search_data."'"." or b.mobile LIKE '".$search_data."' "." or b.username LIKE '".$search_data."'";
                }

                if ($recordid){
                    $condition .= " and a.order_id=$recordid ";
                }

                if ($start_day && $end_day && $start_day!=$end_day){
                    $condition .= "  and a.created_at between '".$start_day."' and '".$end_day."'";
                }

                 $ex_page = $_P['ex_page']?$_P['ex_page']:1;
                 $sql = " SELECT a.id,a.uid,a.shangjiaid,a.address,a.created_at,a.updated_at,a.status,a.workerid,b.avatar,b.nickname,b.username,b.mobile,b.fromuid,c.name,d.name as shangjianame,e.fee,e.mobile as order_mobile,f.username as workenname,g.nickname as form_nickanme
                ,e.datetime,e.address as raddress,e.formtwo,e.addinfo,e.option FROM "
                    .tablename(t_shangjia_address_user_course)." AS  a ".
                    " LEFT JOIN ".tablename(t_fans)." AS b ON a.uid=b.uid and b.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia_course)." AS c ON a.course_id=c.id and c.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_shangjia)." AS d ON a.shangjiaid=d.id ".
                    " LEFT JOIN ".tablename(t_record)." AS e ON a.order_id=e.id and  e.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_worker)." AS f ON e.workerid=f.uid and f.themeid=$themeid".
                    " LEFT JOIN ".tablename(t_fans)." AS g ON b.fromuid=g.uid and g.themeid=$themeid".
                    " WHERE a.themeid=$themeid and e.status=1 ".$condition.
                    "  order by a.created_at desc limit ". ($ex_page - 1) * $page_limit . ",$page_limit ";

                $list = db_select($sql);


                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            if ($row['status']){
                                $row['status'] = '已核销';
                            }else{
                                $row['status'] = '未核销';
                            }

                            $check_name = '';
                            if ($row['workerid']){
                                $r = Worker::getWokerName($_S,$themeid,$row['workerid']);
                                $check_name=$r['workername']==1?'后台管理员':$r['workername'];
                            }
                            $row['check_name'] = $check_name;
                            if ($row['status']!='已核销'){
                                $row['checked_at']='';
                            }else{
                                $row['checked_at'] = $row['updated_at'];
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
//                }
            }
            //新版本导出合并

            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'用户课程校区选择记录',$themeid,$is_end,$pagesize);
        }
        if (checksubmit('export_submit2',true)){
            self::newWait();
            exit();
        }
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/education/flag/course', $return_clicent);
    }

    public function getSearchRes()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $search = $_P['search_info']?$_P['search_info']:'';
        if (!$search){
            return show_json(0,['msg'=>'参数缺失']);
        }
        if ($search){
            $search = '%'.$search.'%';
        }
        //通过手机号  微信昵称搜索订单记录
        $res = EducationModel::searchOrderInfo($themeid,$search);
        if (!$res){
            return show_json(0,['msg'=>'未查询到用户付款信息']);
        }else{
            return show_json(1,['msg'=>'success','data'=>$res]);
        }
    }

    public function getCanSelectCourse()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $shangjiaid = $_P['shangjia_id']?$_P['shangjia_id']:0;
        //获取当前用户已选课程的ids
        $has_list = EducationModel::getCourseList($themeid,$shangjiaid,'');
        return show_json(0,['msg'=>'操作成功','data'=>$has_list]);
    }

    public function editCourse()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $shangjiaid = $_P['shangjia_id']?$_P['shangjia_id']:0;
        $course_id = $_P['course_id'];
        $uid = $_P['uid'];

        //获取当前用户已选课程的ids
        $has_list = EducationModel::getUserCanEditCourseList($themeid,$shangjiaid,$uid);
        return show_json(0,['msg'=>'操作成功','data'=>$has_list]);
    }

    public function sureEditCourse()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $course_id = $_P['course_id'];//记录id
        $shangjia = $_P['shangjia'];
        $course = $_P['course'];
        $adress = $_P['adress'];
        if (!$course_id){
            return show_json(0,['msg'=>'记录参数缺失']);
        }
        if (!$shangjia){
            return show_json(0,['msg'=>'商家参数缺失']);
        }
        if (!$course){
            return show_json(0,['msg'=>'修改课程缺失']);
        }
        if (!$adress){
            return show_json(0,['msg'=>'修改地址缺失']);
        }
        $data = [
            'shangjiaid'=>$shangjia,
            'course_id'=>$course,
            'address'=>$adress,
        ];
        $where = [
            'id'=>$course_id,
            'themeid'=>$themeid
        ];
        $data['updated_at'] = date("Y-m-d H:i:s",time());
        $res = db_update(t_shangjia_address_user_course,$data,$where);
        if (!$res){
            return show_json(0,['msg'=>'修改失败']);
        }else{
            return show_json(1,['msg'=>'修改成功']);
        }
    }

    public function newWait()
    {
        global $_G,$_P,$_S,$_C;
        $condition = "";
        //没有员工的定单

        $nowoker = intval($_P['noworker']);
        $themeid = intval($_P['themeid']);
        $shangjiaid = intval($_P['shangjiaid']);

        $config =    Theme::getConfig($themeid);

        $endtime = !$_P['createtime']['end']?time():$_P['createtime']['end'];
        if ($nowoker==-1 || $nowoker>0){
            if ($nowoker>0){$starttime=$nowoker;}
            $condition .= Worker::getWorkerListSql(' and (ord.status > 0 || ord.status =-2) and ord.workerid not');
        }
        $condition.= " and ord.addtime > '{$starttime}' and ord.addtime <= '{$endtime}' ";

//        if($_P['op2'] == 'scan'){
//            $condition.= " and (ord.pid = '{$id}' or ord.id = '{$id}') ";
//        }

        $condition .= " and ord.themeid = '{$themeid}' ";

        $workerid = $_P['workerid'];
//        if(!empty($workerid)){
//            $condition .= Worker::getWokerid($system,$workerid,' and ord.workerid ');
//        }
        if(!empty($_P['zhijie'])){
            $condition.= " and ord.fromuid = '{$workerid}'  ";
        }
        $fromuid = $_P['fromuid'];
        if(!empty($fromuid)){
            $condition.= " and (ord.fromuid = '{$fromuid}' )";
        }

        $qrimgid = $_P['qrimgid'];
        if(!empty($qrimgid)){
            $condition.= " and (ord.qrimgid = '{$qrimgid}' )";
        }

        if(!isset($_P['type'])){
            $type = -1;
        }else{
            $type = intval($_P['type']);
        }

        if($type == 10){
            $condition.= " and ord.isfinish = '0' and ord.xunifinish = '0' and ord.status >0 and ord.tuannum>1";
        }elseif($type == 17){
            $condition.= " and ord.isfinish = '0' and ord.xunifinish = '0' and ord.status >0  and ord.tuannum=1";
        }elseif($type == 11){
            $condition.= " and (ord.isfinish = '1' or ord.xunifinish = '1') and ord.status >0 ";
        }elseif($type == 12){
            $condition.= " and ord.isfirstbuy = 1 and ord.status >0 ";
        }elseif($type == 25){
            $condition.= " and ord.type = 8 and ord.status >0 ";
        }elseif($type == 26){
            $userlist = db_select("SELECT uid FROM " . tablename(t_record) ." where type = 8 and status >0 group by uid");
            if (!empty($userlist)) {
                if (!empty($userlist)){
                    $userlist2=[];
                    foreach ($userlist as $key => $item) {
                        $userlist2[]=$item['uid'];
                    }
                    $condition .=  " and uid not in (" . implode(",",$userlist2) . ")";
                }
            }
            $condition.= " and ord.type != 8 and fee<>'{$config['yukuan']}' and ord.status >0 ";
        }elseif($type == 34){
            $condition.= " and ord.type != 8 and fee='{$config['yukuan']}' and ord.status >0 ";
        }elseif($type >= 0){
            $condition.= " and ord.type = '{$type}'  ";
        }
        if(!isset($_P['status'])){
            $status = -10;
        }else{
            $status = intval($_P['status']);
        }

        if($status == 21){
            $condition.= " and ord.jiagetype = '{$config['joinname']}'  ";
        }elseif($status == 22){
            $condition.= " and ord.jiagetype = '{$config['joinname2']}'  ";
        }elseif($status == 23){
            $condition.= " and ord.jiagetype = '{$config['joinname3']}'  ";
        }elseif($status == -9){
            $condition.= " and ord.type = 0  ";
        }elseif($status >= -5){
            $condition.= " and ord.status = '{$status}'  ";
        }

        if($status != -2 && $_P['op2'] != 'scan' && empty($_P['keyword'])){
            $condition.= " and ord.status <> '-2'  ";
        }

        if($status == -9){
            $sorttype = ',ord.tuannum desc,ord.addtime desc ';
        }elseif($type == 25){
            $sorttype = ',ord.addtime desc ';
        }elseif($type > 9){
            $sorttype = ',ord.pid desc, ord.type asc, ord.addtime asc';
        }else{
            $sorttype = ',ord.addtime desc ';
        }

        $keyword = trim($_P['keyword']);
        if(!empty($keyword)){
            if (intval($keyword)>10000 && intval($keyword)<30000) {
                $tempa = intval($keyword)-10000;
                $condition.= " and (ord.pid = '". $tempa . "' or ord.id = '". $tempa. "') ";
            } else {
                $condition.= " and (ord.nickname like '%{$keyword}%' or ord.username like '%{$keyword}%' or ord.mobile like '%{$keyword}%'  or ord.option like '%{$keyword}%' or ord.address like '%{$keyword}%' or ord.datetime like '%{$keyword}%' or ord.addinfo like '%{$keyword}%')";
            }
        }

        if(!empty($_P['address'])){
            $condition.= " and FIND_IN_SET('" . $_P['address'] . "' ,REPLACE(`address`, '|', ','))";
        }
        if(!empty($_P['formtwo'])){
            $condition.= " and FIND_IN_SET('" . $_P['formtwo'] . "' ,REPLACE(`formtwo`, '|', ','))";
        }

        if(!empty($_P['shops'])){
            if ($config['shopstype']!=8){
                $condition.= " and FIND_IN_SET('" . $_P['shops'] . "' ,REPLACE(`option`, '|', ','))";
            }
        }
        if ($_S['softstyle']==5) {
            $tuanzhang = $config['jmbiemingwenzi'];
            $danmai = $config['jmbiemingwenzi2'];
        }else{
            $tuanzhang = '团长';
            $danmai = '单买';
        }
        $worklist = Worker::getworkerlist($_S,$themeid);
        $statustr = array("未支付","已支付","已核销","线下定单","已退款","虚拟定单");
        $groupstr = array("拼团中","拼团成功","虚拟成团");
        $member_from=array('未标记','老客户','新客户');
        $typestr = array($tuanzhang,"团员","补余款",$danmai);

        $shangjia_list = db_select("SELECT id,name FROM ".tablename (t_shangjia),array(),'id');

        $course_list = db_select("SELECT id,name FROM ".tablename (t_shangjia_course),array(),'id');

        $gift_list = db_select("SELECT id,name FROM ".tablename (t_shangjia_gift),array(),'id');

        $coupon_list = db_select("SELECT id,name FROM ".tablename (t_shangjia_coupon),array(),'id');

        $order_course_sql = " SELECT  uc.shangjiaid,uc.order_id,
                              ord.id,ord.uid,ord.pid,ord.nickname,ord.username,ord.mobile,
                              ord.fee,ord.workerid,ord.fromuid,ord.status,ord.isfinish,
                              ord.tuannum,ord.addtime,ord.refundtime,ord.type,
                              group_concat( uc.course_id) as course_ids,
                              group_concat(ug.gift_id) as gift_ids,
                              group_concat( uc.address) as addresss,
                              group_concat(up.coupon_id) as coupon_ids
                      FROM " . tablename(t_shangjia_address_user_course) . "  uc
                      INNER JOIN ".tablename(t_record)." ord ON uc.order_id=ord.id
                      LEFT JOIN ".tablename(t_shangjia_user_gift)." ug ON ug.shangjiaid=uc.shangjiaid AND ug.order_id=uc.order_id
                      LEFT JOIN ".tablename(t_shangjia_user_coupon)." up ON up.shangjiaid=uc.shangjiaid AND up.order_id=uc.order_id
                      where uc.shangjiaid=$shangjiaid
                      GROUP BY uc.order_id,uc.shangjiaid 
                      ORDER BY uc.shangjiaid ASC,uc.order_id asc".$sorttype;

        $order_course_list = db_select($order_course_sql);
        $shangjia_data = array();

        foreach ($order_course_list  as  $v){
            $shangjiaid = $v['shangjiaid'];


            $course_names = '';
            if($v['course_ids']){     //课程
                  $course_ids_array = explode(',',$v['course_ids']);
                  $address_array = explode(',',$v['addresss']);
                  if(count($course_ids_array)>1){
                      foreach ($course_ids_array as $k =>$c){
                          $name = $course_list[$c]['name'].'['.$address_array[$k].']';
                          $course_names .= $k>0?'|'.$name:$name;
                      }
                  }else{
                      $course_id = $course_ids_array[0];
                      $course_names = $course_list[$course_id]['name'].'['.$address_array[0].']';
                  }
            }

            $gift_names = '';
            if($v['gift_ids']){      //礼物
                $gift_ids_array = explode(',',$v['gift_ids']);
                if(count($gift_ids_array)>1){
                    foreach ($gift_ids_array as $k =>$g){
                        if($k>0){
                            $gift_names .= '|'.$gift_list[$g];
                        }else{
                            $gift_names .= $gift_list[$g];
                        }
                    }
                }else{
                    $gift_id = $gift_ids_array[0];
                    $gift_names = $gift_list[$gift_id];
                }
            }

            $coupan_names = '';
            if($v['coupon_ids']){   //优惠券
                $coupon_ids_array = explode(',',$v['coupon_ids']);
                if(count($coupon_ids_array)>1){
                    foreach ($coupon_ids_array as $k =>$p){
                        if($k>0){
                            $coupan_names .= '|'.$coupon_list[$k];
                        }else{
                            $coupan_names .= $coupon_list[$k];
                        }
                    }
                }else{
                    $coupon_id = $coupon_ids_array[0];
                    $coupan_names = $coupon_list[$coupon_id];
                }
            }

            //订单中顺序处理
            if(!empty($v['fromuid'])){
                $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " 
                                WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$v['fromuid']));
                $v['nickname2'] = $fans['nickname'];
            }
            if(!empty($v['workerid'])){
                $r = Worker::getWokerName($_S,$themeid,$v['workerid'],$worklist);
                $v['workername']=$r['workername'];
                $v['teamname']=$r['teamname'];
                $v['companyname']=$r['companyname'];
            }else{
                $v['workername']='';
                $v['teamname']='';
                $v['companyname']='';
            }
            if ($v['type']==0){
                $v['tuanid'] = $v['id']+10000;
            }elseif ($v['type']==9){
                $v['tuanid'] = 0;
            }else{
                $v['tuanid'] = $v['pid']+10000;
            }
            $v['is_member'] = $member_from[$v['is_member']]?$member_from[$v['is_member']]:'';
            if ($_S['wxapp']==$v['uniacid']){
                $v['uniacid'] = "小程序";
            }else{
                $v['uniacid'] = "H5";
            }
            $v['nickname']=str_replace('"',"",$v['nickname']);
            $v['nickname']=str_replace(',',"",$v['nickname']);
            $v['nickname2']=str_replace('"',"",$v['nickname2']);
            $v['nickname2']=str_replace(',',"",$v['nickname2']);
            if (empty($v['nickname2'])){
                $v['nickname2']=$v['fromuid'];
            }
            $v['username']=str_replace('"',"",$v['username']);
            $v['username']=str_replace(',',"",$v['username']);

            $v['beizhu']=str_replace('"',"",$v['beizhu']);
            $v['beizhu']=str_replace(',',"，",$v['beizhu']);

            //仿照订单二次循环处理
            if($v['addtime'] > 0){
                $v['addtime']  = date('Y-m-d H:i:s',$v['addtime']);
            }
            //虚拟成团
            if ($v['xunifinish']==1){
                $v['isfinish'] = 2;
            }
            if($v['status'] > 0){
                $v['status'] = $statustr[$v['status']];
                $v['isfinish'] = $groupstr[$v['isfinish']];
            }elseif( $v['status'] == -1){
                $v['status'] = $statustr[4];
                $v['isfinish'] = "";
            }elseif( $v['status'] == -2){
                $v['status'] = $statustr[5];
                $v['isfinish'] = $groupstr[$v['isfinish']];
            }else{
                $v['status'] = $statustr[$v['status']];
                if ($v['status'] == 0) {
                    $v['isfinish'] = "";
                }else{
                    $v['isfinish'] = $groupstr[$v['isfinish']];
                }
            }
            if ($v['type']==8){$v['type']=2;}
            if ($v['type']==9){$v['type']=3;}
            $v['type'] = $typestr[$v['type']];
            $v['id'] = (int)$v['id']+9000;

            unset($v['shangjiaid']);
            unset($v['order_id']);
            unset($v['course_ids']);
            unset($v['gift_ids']);
            unset($v['coupon_ids']);
            unset($v['addresss']);
            $v['course_names'] = $course_names;
            $v['coupan_names'] = $coupan_names;
            $v['gift_names'] = $gift_names;

            if(isset($shangjia_data[$shangjiaid])){
                $shangjia_data[$shangjiaid]['data'][] = $v;
            }else{
                $shangjia_info = $shangjia_list[$shangjiaid];
                $shangjia_name = $shangjia_info?$shangjia_info['name']:'';
                $shangjia_data[$shangjiaid] = [
                       'id' => $shangjiaid,
                       'name' => $shangjia_name,
                       'data' => [$v]
                ];
            }
        }

        $shangjia_data = array_values($shangjia_data);
        $list = $shangjia_data[0]['data'];
        $header = $this->getHeaderArr($_C,$_S);


        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
        if ($list){
            $size = ceil(count($list) / 500);
            for ($i = 0; $i < $size; $i++) {
                $buffer = array_slice($list, $i * 500, 500);
                foreach ($buffer as $row) {
                    foreach ($keys as $key) {
                        $data[] = $row[$key];
                    }
                    if (isset($data)){
                        $user[] = implode("\t ,", $data) . "\t ,";
                        unset($data);
                    }
                }
                $html .= implode("\n", $user)."\n";
                unset($user);
            }
        }
        $file_name = $shangjia_data[0]['name'];
        //新版本导出合并
        Util::WxJump($_S,$html,''.$file_name.'',$themeid,1,1);
//        $export_excel = $this->table_export($shangjia_data[0]['name'],0,1,$header,$shangjia_data[0]['data']);

    }

    public function getHeaderArr($config,$system)
    {
        $header= [];
        $header['id'] = '定单号';
        if (!empty($system['wxapp'])){
            $header['uniacid'] = '来自';
        }
        $header['nickname'] = '微信昵称';
        $header['username'] = '姓名';
        $header['mobile'] = '电话';
        if ($system['jiage']>0) {
            $header['jiagetype'] = $config['duojiagetips'];
        }
        if (!empty($config['datetime'])) {
            $header['datetime']= $config['datetime'];
        }
        if (!empty($config['address'])) {
            $header['address'] = $config['address'];
        }
        if (!empty($config['formtwo'])) {
            $header['formtwo'] = $config['formtwo'];
        }
        if (!empty($config['addinfo'])) {
            $header['addinfo']= $config['addinfo'];
        }
        if (!empty($config['shops']) && $config['shopstype']!=4 && $config['shopstype']!=5 ) {
            $header['option'] = $config['shops'];
        }
        $header['fee'] = '金额';
        $header['nickname2'] = '推荐';
        $header['status'] = '状态';
        if ($system['ruanjian']!==1) {
            $header['tuanid'] = '团号';
            $header['tuannum'] = '团人数';
            $header['type'] = '身份';
            $header['isfinish'] = '拼团状态';
        }
        if ($config['groupprice2']>0){
            $header['gruoptips'] = '类型';
        }
        if($config['isicon'] > 0){
            $header['lightsum'] = '点亮数';
        }
        if ($system['qrlist']==1) {
            $header['qrimgid'] = '二维码ID';
            $header['qrimg'] = '二维码';
        }
        $header['addtime'] = '时间';
        if ($system['is_multiple_merchants']) {
            $header['companyname']='公司';
        }
        $header['teamname']='团队';
        $header['workername']='员工';
        $header['is_member']='来源';
        $header['member_beizhu']='备注';
        if (!empty($config['shops']) && ($config['shopstype']==4 || $config['shopstype']==5) ) {
            $shops_lists = Record::get_shops_list($config);
            if (!empty($shops_lists)) {
                foreach ($shops_lists as $key => $value) {
                    if (!empty($value)) {
                        $header['shops'.$key]=$value;
                        $value = preg_replace('#[^\x{4e00}-\x{9fa5}A-Za-z0-9_.,|，\-]#u', '', $value);
                    }
                }
            }
        }
        $header['course_names']='课程';
        $header['coupan_names']='优惠券';
        $header['gift_names']='礼品';
        return $header;
        $new_header = [];
        foreach ($header as $k =>$v){
            $new_header[] = ['code'=>$k,'name'=>$v];
        }
        return $new_header;
    }

    public function table_export($sj_name = '',$sheet_page='', $total_page='',$header,$data, $excel='')
    {
        
        if ($sheet_page==0){
            $excel = new PHPExcel();
            $first_sheet_title = $sj_name.'订单数据';
            $excel->setActiveSheetIndex(0);
            $this->sheet_more_sign($header,$data, $excel);
            $excel->getActiveSheet()->setTitle($first_sheet_title);
        }
        if ($sheet_page>0){
            $first_sheet_title = $sj_name.'订单数据';
            $excel->createSheet();
            $excel->setActiveSheetIndex($sheet_page);
            $this->sheet_more_sign($header,$data, $excel);
            $excel->getActiveSheet()->setTitle($first_sheet_title);
        }
        if ($sheet_page ==0 && $sheet_page+1 != $total_page){
            return $excel;
        }
        if ($sheet_page+1 == $total_page){
            header('Content-Type: application/vnd.ms-excel; charset=utf-8');
            header('Cache-Control: max-age=0');
            header('Content-Disposition:attachment;filename="'.$first_sheet_title.'.xlsx"');
            $write = PHPExcel_IOFactory::createWriter($excel,'Excel2007');
            $write->save('php://output');
            if ($sheet_page == 0) {
                return $excel;
            }
        }
    }

    public function sheet_more_sign($header,$data,$excel)
    {
        $zimu = [];
        for($z="A";$z<="Z";$z++){
            $zimu[]=$z;
        }
        $aoo=array_slice($zimu,0,26);
        for($i=0;$i<count($header);$i++){
            $excel->getActiveSheet()->setCellValue($aoo[$i].'1',$header[$i]['name']);
        }

        $i=2;
        foreach ($data as $k =>$v){
            foreach ($header as $kk => $vv){
                if ($aoo[$kk]){
                    $col_key = $aoo[$kk].$i;
                    $excel->getActiveSheet()->setCellValue("$col_key",$v[$vv['code']]);
                }
            }
            $i+=1;
        }
    }
}